import { message } from 'antd';
import { isSuccess } from '@/utils/request';

import { salaryRecheck, payoffService } from '@/services/salaryManage/salaryCalculate';

import TabsMenuRight from '@/pages/SalaryManage/components/TabsMenuRight';
import modelType from '@/pages/SalaryManage/SalaryCalculate/constant/modelTypeConstant';

const { latestSalaryYearMonth, queryGrantTableBodyData, queryGrantTableHeadData } = salaryRecheck;

const { getTableToolButtons, doPayoff, exportFile, getExportInfo } = payoffService;

function* getState(select, namespace) {
    return yield select(state => state[namespace]);
}

function* searchPostData(select, namespace) {
    const currentState = yield* getState(select, namespace);

    const periodStr = currentState.period || '';
    const year = periodStr.substr(0, 4);
    const month = periodStr.substr(5);

    return {
        year,
        month: month ? String(parseInt(month, 10)) : month,
        page: {
            pageNo: currentState.pagination.current,
            pageSize: currentState.pagination.pageSize
        },
        ...currentState.searchModel,
        requestBusiUnit: 2,
        nodeCode: 3
    };
}

const namespace = 'detailRecheckModel';
const shareNamespace = 'payoffSharedModel';
const detailRecheckModel = {
    namespace,
    state: {
        period: null,
        searchModel: {
            departmentCode: null
        },
        checkButtonList: [],
        tableLoading: false,
        rowKey: 'id',
        pagination: {
            current: 1,
            pageSize: 10
        },
        tableHeader: [],
        dataSource: [],
        currentRecord: {},

        modalVisible: false,
        nodeCode: 3
    },
    reducers: {
        [modelType.SET_MULTI_STORE](state, action) {
            return {
                ...state,
                ...action.payload
            };
        },

        [modelType.SET_LOADING](state, action) {
            return {
                ...state,
                ...action.payload
            };
        },

        [modelType.RESET_STORE](state, action) {
            return {
                ...state,
                checkButtonList: [],
                tableHeader: [],
                period: null,
                dataSource: [],
                footerSource: null,
                pagination: {
                    current: 1,
                    pageSize: 10
                },
                searchModel: {
                    downAbnormalTipIndex: 5,
                    upAbnormalTipIndex: 5,
                    salaryRateKpiInd: '1',
                    ...action.payload
                }
            };
        },
        /**
         * 更变月份
         * @param action.payload 月份
         */
        [modelType.SET_PERIOD](state, action) {
            const { payload: period } = action;

            return {
                ...state,
                period
            };
        },

        [modelType.SET_SEARCH_CONDITION](state, action) {
            const { searchModel } = state;
            return {
                ...state,
                searchModel: {
                    ...searchModel,
                    ...action.payload
                }
            };
        },

        [modelType.SET_PAGE_INFO](state, action) {
            const { pageSize, total, pageNo: current, rows: dataSource } = action.payload.data;

            const pagination = {
                ...state.pagination,
                pageSize: pageSize || 10,
                current: current || 1,
                total
            };

            return {
                ...state,
                dataSource,
                pagination
            };
        },

        [modelType.INIT_STORE](state) {
            return {
                ...state,
                checkButtonList: [],
                period: null,
                dataSource: [],
                tableHeader: []
            };
        },

        [modelType.SET_PAGINATION](state, action) {
            const pagination = {
                ...state.pagination,
                current: action.payload.current || state.pagination.current,
                pageSize: action.payload.pageSize || state.pagination.pageSize
            };

            return {
                ...state,
                pagination
            };
        },

        [modelType.SET_TABLE_HEADER](state, action) {
            return {
                ...state,
                tableHeader: action.payload
            };
        },

        [modelType.SET_CURRENT_RECORD](state, action) {
            return {
                ...state,
                currentRecord: action.payload
            };
        },

        [modelType.SET_MODAL_VISIBLE](state, action) {
            return {
                ...state,
                modalVisible: action.payload
            };
        }
    },
    effects: {
        *[modelType.E_INIT](state, { put, call, select, all }) {
            // 默认第一页
            yield put({
                type: modelType.SET_PAGINATION,
                payload: {
                    current: 1
                }
            });

            // 默认无选中
            yield put({
                type: modelType.SET_SELECTED_ROW,
                payload: []
            });


            let postData = yield* searchPostData(select, namespace);

            // 如果不是切换月份，则调用接口获取默认年月
            if (!state.payload) {
                const response = yield call(latestSalaryYearMonth, {
                    organizationCode: postData.organizationCode
                });

                if (!isSuccess(response)) {
                    message.error(response.msg);
                    return;
                }
                // 未配置月模板，不请求数据
                if (!response.data.year || !response.data.month) {
                    yield put({
                        type: modelType.INIT_STORE
                    });
                    yield put({
                        type: `${shareNamespace}/${modelType.E_SHARED_STATE}`,
                        payload: {
                            sharePeriod: null
                        }
                    });
                    return;
                }
                const { year, month } = response.data;

                // 设置默认月份
                yield put({
                    type: modelType.SET_PERIOD,
                    payload: `${year}-${(month < 10 ? '0' : '') + month}`
                });
            } else {
                // 设置默认月份
                yield put({
                    type: modelType.SET_PERIOD,
                    // payload: moment().from(new Date()).format('YYYY-MM')
                    payload: state.payload
                });
            }

            postData = yield* searchPostData(select, namespace);

            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: true }
            });
            const [checkButtonsResponse, infoResponse, headerResponse, recordResponse] = yield all([
                // 操作按钮列表获取
                call(getTableToolButtons, {
                    year: postData.year,
                    month: postData.month,
                    organizationCode: postData.organizationCode
                }),
                // 头部信息
                call(getExportInfo, {
                    year: postData.year,
                    month: postData.month,
                    organizationCode: postData.organizationCode
                }),

                // 查询表头数据
                call(queryGrantTableHeadData, {
                    year: postData.year,
                    month: postData.month,
                    contrastType: postData.contrastType || '1',
                    organizationCode: postData.organizationCode
                }),
                // 查询表格表体数据
                call(queryGrantTableBodyData, postData)
            ]);
            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: false }
            });

            let checkButtonList = [];
            if (isSuccess(checkButtonsResponse)) {
                checkButtonList = checkButtonsResponse.data;
            } else {
                message.error(checkButtonsResponse.msg);
            }

            if (!isSuccess(infoResponse)) {
                message.error(infoResponse.msg);
            } else {
                yield put({
                    type: modelType.SET_CURRENT_RECORD,
                    payload: infoResponse.data
                });
            }

            let tableHeader = [];
            if (isSuccess(headerResponse)) {
                tableHeader = headerResponse.data;
            } else {
                message.error(headerResponse.msg);
            }

            yield put({
                type: modelType.SET_MULTI_STORE,
                payload: {
                    checkButtonList,
                    tableHeader
                }
            });

            if (isSuccess(recordResponse)) {
                yield put({
                    type: modelType.SET_PAGE_INFO,
                    payload: recordResponse
                });
            } else {
                message.error(`${recordResponse.msg}`);
            }
        },

        *[modelType.E_SEARCH](s, { put, call, select, all }) {
            // 设置查询条件
            if (s.payload) {
                yield put({
                    type: modelType.SET_SEARCH_CONDITION,
                    payload: s.payload
                });

                yield put({
                    type: modelType.SET_PAGINATION,
                    payload: {
                        current: 1
                    }
                });
            }

            yield put({
                type: modelType.SET_SELECTED_ROW,
                payload: []
            });

            const postData = yield* searchPostData(select, namespace);

            if (!postData.year || !postData.month) {
                message.error('请选择薪资年月');
                return;
            }

            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: true }
            });
            const [headerResponse, infoResponse, response] = yield all([
                call(queryGrantTableHeadData, {
                    year: postData.year,
                    month: postData.month,
                    contrastType: postData.contrastType || '1',
                    organizationCode: postData.organizationCode
                }),
                // 头部信息
                call(getExportInfo, {
                    year: postData.year,
                    month: postData.month,
                    organizationCode: postData.organizationCode
                }),
                call(queryGrantTableBodyData, postData)
            ]);
            if (!isSuccess(response)) {
                message.error(response.msg);
            } else {
                yield put({
                    type: modelType.SET_PAGE_INFO,
                    payload: response
                });
            }

            if (!isSuccess(infoResponse)) {
                message.error(infoResponse.msg);
            } else {
                yield put({
                    type: modelType.SET_CURRENT_RECORD,
                    payload: infoResponse.data
                });
            }

            let tableHeader = [];
            if (isSuccess(headerResponse)) {
                tableHeader = headerResponse.data;
            } else {
                message.error(headerResponse.msg);
            }

            yield put({
                type: modelType.SET_MULTI_STORE,
                payload: { tableHeader }
            });

            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: false }
            });
        },
        // 重置
        *[modelType.E_RESET](state, { put }) {
            yield put({
                type: modelType.RESET_STORE,
                payload: state.payload
            });
        },
        *[modelType.E_SEARCH_CONDITION](state, { put }) {
            yield put({
                type: modelType.SET_SEARCH_CONDITION,
                payload: state.payload
            });
            state.callback()
        },
        // 更新头部导出信息
        *headerInfo(s, { put, call, select, all }) {
            const postData = yield* searchPostData(select, namespace);
            const [infoResponse] = yield all([
                // 头部信息
                call(getExportInfo, {
                    year: postData.year,
                    month: postData.month,
                    organizationCode: postData.organizationCode
                })
            ]);

            if (!isSuccess(infoResponse)) {
                message.error(infoResponse.msg);
            } else {
                yield put({
                    type: modelType.SET_CURRENT_RECORD,
                    payload: infoResponse.data
                });
            }
        },
        *[modelType.E_TABLE_PAGE_CHANGE](state, { put }) {
            yield put({
                type: 'setPagination',
                payload: state.payload
            });
            yield put({ type: 'search' });
        },
        // 执行付款
        *[modelType.E_PAYOFF](s, { put, call, select }) {
            const postData = yield* searchPostData(select, namespace);
            const response = yield call(doPayoff, {
                year: postData.year,
                month: postData.month,
                organizationCode: postData.organizationCode
            });

            if (!isSuccess(response)) {
                message.error(`操作失败：${response?.msg}`);
                return;
            }
            message.success(response.msg);
            yield put({
                type: modelType.E_INIT,
                payload: `${postData.year}-${(postData.month < 10 ? '0' : '') + postData.month}`
            });
        },
        // Excel导出弹窗
        *[modelType.E_EXCEL_EXPORT_MODEL](s, { put }) {
            yield put({
                type: modelType.SET_MULTI_STORE,
                payload: {
                    modalVisible: s.payload
                }
            });
        },
        // Excel导出
        *[modelType.E_EXCEL_EXPORT](s, { put, select, call }) {
            const postData = yield* searchPostData(select, namespace);
            const response = yield call(exportFile, {
                year: postData.year,
                month: postData.month,
                departmentCode: postData.departmentCode,
                organizationCode: postData.organizationCode,
                ...s.payload
            });
            yield put({
                type: 'headerInfo'
            });
            s.callback(response);
        }
    }
};

detailRecheckModel.state.RecheckMenuRight = TabsMenuRight

export default detailRecheckModel;
